package com.nowcoder.community.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.nowcoder.community.util.CommunityUtils;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
@RequestMapping("/Alpha")
public class AlphaController {
    @RequestMapping("/hello")
    @ResponseBody
    public String sayHello(){
        return "Hello";
    }

    @RequestMapping("/http")
    public void http(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println(request.getMethod());
        System.out.println(request.getParameter("code"));

        response.setContentType("text/html;charset=utf-8");

        PrintWriter writer =response.getWriter();
        writer.write("<h1>智慧树<h1>");
        writer.close();
    }

    @RequestMapping(path = "/student/{id}",method = RequestMethod.GET)
    @ResponseBody
    public String getStudent(@PathVariable("id") int id){
        System.out.println(id);
        return "王潇";
    }

    @RequestMapping(path = "/teacher",method = RequestMethod.GET)
    public ModelAndView getTeacher() {
        ModelAndView mav =new ModelAndView();
        mav.addObject("name","王潇");
        mav.addObject("age","18");
        mav.setViewName("/demo/view");
        return mav;
    }

    @RequestMapping(path = "/cookie/set",method = RequestMethod.GET)
    @ResponseBody
    public  String setCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie("code","1234");
        cookie.setPath("/community/Alpha");
        cookie.setMaxAge(600);
        response.addCookie(cookie);
        return  "add cookie";
    }

    @RequestMapping(path = "/cookie/get",method = RequestMethod.GET)
    @ResponseBody
    public String getCookie(@CookieValue("code") String code) {
        System.out.println(code);
        return "get cookie";
    }
    @RequestMapping(path = "/session/set",method = RequestMethod.GET)
    @ResponseBody
    public String setSession(HttpSession session) {
        session.setAttribute("name","王晓");
        session.setAttribute("pwd","55555");
        return "get session;";
    }



    @RequestMapping(path = "/session/get",method = RequestMethod.GET)
    @ResponseBody
    public String getSession(HttpSession session) {
        System.out.println(session.getAttribute("name"));
        System.out.println(session.getAttribute("pwd"));
        return "get session";
    }

    @RequestMapping(path = "/ajax",method = RequestMethod.POST)
    @ResponseBody
    public String testAJAX(String name, int age) {
        System.out.println("name");
        System.out.println(name);
        System.out.println(age);
        return CommunityUtils.getJsonString(0,"success");
    }

}
